/* ************************************************************************

   Copyright:

   License:

   Authors: SALMON Charles

************************************************************************ */

/* ************************************************************************

#asset(bip/*)
#asset(thirdparty/jsonrpc.js)
#asset(qx/icon/Oxygen/32/*)
#asset(qx/icon/Oxygen/16/*)
#asset(qx/icon/Oxygen/22/*)
#asset(qx/icon/Oxygen/48/*)


************************************************************************ */

/**
 * This is the main application class of your custom application "bip"
 */
qx.Class.define("bip.Application",
{
  extend : qx.application.Standalone,
  
  events :
  {
    /**
     * Data event fired after the model has been created. The data will be the
     * created model.
     */
    "loaded" : "qx.event.type.Data",

    /**
     * Fired when an error (aborted, timeout or failed) occurred
     * during the load. If you want more details, use the {@link #changeState}
     * event.
     */
    "error" : "qx.event.type.Event"
  },
  
  properties :
  {
    
    state : {
      check : [
        "configured", "queued", "sending", "receiving",
        "completed", "aborted", "timeout", "failed"
      ],
      init : "configured",
      event : "changeState"
    }
  },
  
  /*
   *****************************************************************************
      STATICS
   *****************************************************************************
   */
  statics : {
		setState: function(state, description) {
			if (description == null) {
				qx.core.Init.getApplication().getCurrentPage().getPage().setState(state);
			} else {
				qx.core.Init.getApplication().getCurrentPage().getPage().setStateWithDescription(state,description);
			}
		},
		
		getToolBar: function() {
			return qx.core.Init.getApplication().getMainView().getChildControl("toolbar");
		},
		
		getPagesDesktop: function() {
			return qx.core.Init.getApplication().getMainView().getChildControl("pane");
		},
		
		getPortletsDesktop: function() {
			return qx.core.Init.getApplication().getMainView().getChildControl("portlets");
		},
		
		getInstance: function() {
			return qx.core.Init.getApplication();
		}
	},

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */

  members :
  {
    __mainView : null,
    __history : null,
    __pages : null,
    __currentPageName:null,
    
    /**
     * This method contains the initial application code and gets called 
     * during startup of the application
     * 
     * @lint ignoreDeprecated(alert)
     */
    main : function()
    {
      // Call super class
      this.base(arguments);

      // Enable logging in debug variant
      if ((qx.core.Environment.get("qx.debug")))
      {
        // support native logging capabilities, e.g. Firebug for Firefox
        qx.log.appender.Native;
        // support additional cross-browser console. Press F7 to toggle visibility
        qx.log.appender.Console;
      	var CONNECTED = true;
      }

      /*
      -------------------------------------------------------------------------
        Below is your actual application code...
      -------------------------------------------------------------------------
      */
      
      // Application size
      var APP_WIDTH = 1000;
      var APP_HEIGHT = 600;
      
      // Build main view
    	this.__mainView = new bip.MainView();
    	this.__mainView.setState("unregistered");
    	var marginLeft = Math.round(APP_WIDTH / 2);
      var marginTop = Math.round(APP_HEIGHT / 2);
      this.__mainView.set({width:APP_WIDTH, height:APP_HEIGHT, marginLeft:-marginLeft});
      this.getRoot().add(this.__mainView, {top:20,left:"50%"});
      
      try {
      	if (CONNECTED) {
      		this.mainView();
      	} else {
      		this.siteView();
      	}
      } catch(e) {
      	alert("FATAL ERROR, please contact your administrator :"+e);
      }
    },
    
    
    mainView: function() {
    	// Get back user role
    	var user = bip.rpc.User.getInstance();
    	this.__mainView.setHeaderUser(new qx.type.BaseString(user.getName()).toUpperCase());
    	if (user.getRole() == "BIP_USER") {
    		this.userView();
    	}
    	else if (user.getRole() == "BIP_AUTHOR") {
  			this.authorView();
  		}
    	else if (user.getRole() == "BIP_ADMIN") {
  			this.adminView();
  		}
    	else {
  			alert("FATAL: Unsupported role !");
  		}
    },
    
    adminView: function() {
    	qx.io.PartLoader.require(["admin"],function() {
    			bip.adminview.AdminView.getInstance();
    			//this.getMainContainer().add(this.__mainView, {flex:1});
    			this.getMainView().setState("ready");
    			this.__pages =  bip.adminview.AdminPages.getInstance();
    			this.__initBookmarkSupport();
    	},this);
    },
    
    authorView: function() {
    	qx.io.PartLoader.require(["author"],function() {
    			bip.authorview.AuthorView.getInstance();
    			//this.getMainContainer().add(this.__mainView, {flex:1});
    			this.getMainView().setState("ready");
    			this.__pages =  bip.authorview.AuthorPages.getInstance();
    			this.__initBookmarkSupport();
    			this.load("manage_survey");
    	},this);
    },
    
    userView: function() {
    	qx.io.PartLoader.require(["user"],function() {
    			bip.userview.UserView.getInstance();
    			//this.getMainContainer().add(this.__mainView, {flex:1});
    			this.getMainView().setState("ready");
    			this.__pages =  bip.userview.UserPages.getInstance();
    			this.__initBookmarkSupport();
    			this.load("fill_survey");
    	},this);
    },
    
    siteView: function() {
    	qx.io.PartLoader.require(["site"],function() {
    			bip.siteview.SiteView.getInstance();
    			//this.getMainContainer().add(this.__mainView, {flex:1});
    			this.getMainView().setState("ready");
    			this.__pages =  bip.siteview.SitePages.getInstance();
    			this.__initBookmarkSupport();
    			this.load("welcome");
    	},this);
    },
    
    getMainView: function() {
    	return this.__mainView;
    },
    
    load: function(pageName) {
    	if (this.__currentPageName != pageName) {
    		var pageModel = this.__pages.get(pageName);
    		var winPage = pageModel.getPage();
    		winPage.open();
    		var winPortlet = pageModel.getPortlet();
    		winPortlet.open();
    		bip.Application.getPortletsDesktop().set({width:pageModel.getPortletWidth(), maxWidth:pageModel.getPortletWidth(), minWidth:pageModel.getPortletWidth()});
    		this.__currentPageName = pageName;
    		this.__history.addToHistory(pageName);
      }
    },
    
    getCurrentPage: function() {
    	return this.__pages.get(this.__currentPageName);
    },
    
    setName: function() {
    	
    },
  
  //***************************************************
  // HISTORY SUPPORT
  // ***************************************************
  /**
   * Back button and bookmark support
   */
  __initBookmarkSupport : function()
  {
    this.__history = qx.bom.History.getInstance();
    this.__history.addListener("request", this.__onHistoryChanged, this);

    // Handle bookmarks
    var state = this.__history.getState();
    var name = state.replace(/_/g, " ");
    
    // checks if the state corresponds to a page. 
    // If yes, the application will be initialized with the selected sample
    if (state && this.__pages.isAvailable(state))
    {
      this.setName(name);
      this.load(state);
    } 
  },


  /**
   * Handler for changes of the history.
   * @param e {qx.event.type.Data} Data event containing the history changes.
   */
  __onHistoryChanged : function(e)
  {
    var state = e.getData();

    // is a sample name given
    if (this.__pages.isAvailable(state))
    {
      this.setName(name);
      this.load(state);
    } 
  }
  },

  /*
   *****************************************************************************
      DESTRUCTOR
   *****************************************************************************
   */

  destruct : function()
  {
  	this.__history = this.__currentPageName = null;
    this._disposeObjects( "__mainView","__pages");
  }

});
